<template>
  <div>
    <el-table
      ref="refTable"
      v-loading="isFetching"
      :data="tableData"
      element-loading-text="Loading"
      fit
      style="width: 100%">
      <el-table-column fixed type="expand">
        <template slot-scope="{ row }">
          <el-form
            :ref="`diagnose7_form${row.__fid}`"
            :model="row"
            :rules="rules"
            label-position="right"
            label-width="150px"
            size="small"
            class="table_expand">
            <div style="width: 90%; display: flex; flex-direction: row; justify-content: flex-start; gap: 50px">
              <div>
                <el-form-item label="品项名称" prop="prodName">
                  <template slot="label">
                    <span>品项名称</span>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="填写最终销售单元（总量不超过10个），例如套卡，方案；如只有纯商品，只添加销量最高的前5个。"
                      placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-input v-model="row.prodName" :disabled="row.id" style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="品项定位" prop="prodPosition">
                  <el-select v-model="row.prodPosition" placeholder="请选择" style="width: 180px">
                    <el-option
                      v-for="item in EnumProdPosition"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="可操作周期" prop="operablePeriod">
                  <template slot="label">
                    <span>可操作周期(月)</span>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="填写天数（如满勤，计30天），并备注操作排期规则。"
                      placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-input-number
                    v-model="row.operablePeriod"
                    controls-position="right"
                    :min="0"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="销售责任方" prop="salesResponsibleParty">
                  <template slot="label">
                    <span>销售责任方</span>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="只填主要的销售方，例如①美容师或护士操作环节、②咨询师咨客环节、③医生操作环节"
                      placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-input v-model="row.salesResponsibleParty" style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item label="销售方式" prop="salesMethod">
                  <el-select v-model="row.salesMethod" placeholder="请选择" style="width: 180px">
                    <el-option
                      v-for="item in EnumSalesMethod"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
                <!--操作-->
                <el-form-item>
                  <el-button v-if="isUpdating" type="primary" disabled icon="el-icon-loading" style="width: 120px">
                    提交中
                  </el-button>
                  <el-button
                    v-else-if="row.id === undefined"
                    type="primary"
                    @click="handleSubmitForm(`diagnose7_form${row.__fid}`, true, row)">
                    保存
                  </el-button>
                  <el-button v-else type="warning" @click="handleSubmitForm(`diagnose7_form${row.__fid}`, false, row)">
                    修改
                  </el-button>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="实际售价" prop="actualPrice">
                  <template slot="label">
                    <span>实际售价</span>
                    <el-tooltip class="item" effect="dark" content="填平均成交价" placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-input-number
                    v-model="row.actualPrice"
                    controls-position="right"
                    :min="0"
                    :step="0.01"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="毛利率(%)" prop="grossMargin">
                  <template slot="label">
                    <span>毛利率(%)</span>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="（售价-成本）/售价, 按平均成交价计算"
                      placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-input-number
                    v-model="row.grossMargin"
                    controls-position="right"
                    :min="0"
                    :step="0.01"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="品项启动日期" prop="prodLaunchDate">
                  <template slot="label">
                    <span>品项启动日期</span>
                    <el-tooltip class="item" effect="dark" content="指院内首次政策发布日期" placement="top">
                      <img
                        src="@/assets/images/question_mark.svg"
                        alt="question mark"
                        style="width: 16px; height: 16px; margin: 0 0 0 5px" />
                    </el-tooltip>
                  </template>
                  <el-date-picker
                    v-model="row.prodLaunchDate"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="{ disabledDate: picDisabledDate }"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 180px"></el-date-picker>
                </el-form-item>
                <el-form-item label="销量" prop="salesVolume">
                  <div class="star_level">
                    <el-rate v-model="row.salesVolume" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.salesVolume = 0)">清除</el-button>
                  </div>
                </el-form-item>
                <el-form-item label="顾客反馈" prop="customerFeedback">
                  <div class="star_level">
                    <el-rate v-model="row.customerFeedback" :max="3"></el-rate>
                    <el-button type="info" size="mini" plain @click.stop="() => (row.customerFeedback = 0)">
                      清除
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="占月业绩百分比(%)" prop="monthlyPerformancePct">
                  <el-input-number
                    v-model="row.monthlyPerformancePct"
                    controls-position="right"
                    :min="0"
                    :step="0.01"
                    style="width: 180px"></el-input-number>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        fixed
        prop="prodName"
        label="品项名称"
        align="center"
        width="120"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="prodPosition" label="品项定位" align="center" width="200">
        <template slot-scope="{ row }">
          {{ row.prodPosition | fltProdPosition }}
        </template>
      </el-table-column>
      <el-table-column prop="operablePeriod" label="可操作周期" align="center" width="110">
        <template slot-scope="{ row }">
          {{ row.operablePeriod ? row.operablePeriod + ' 月' : '' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="salesResponsibleParty"
        label="销售责任方"
        align="center"
        width="100"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="salesMethod" label="销售方式" align="center" width="80">
        <template slot-scope="{ row }">
          {{ row.salesMethod | fltSalesMethod }}
        </template>
      </el-table-column>
      <el-table-column prop="actualPrice" label="实际售价" align="center" width="100"></el-table-column>
      <el-table-column prop="grossMargin" label="毛利率" align="center" width="80"></el-table-column>
      <el-table-column prop="prodLaunchDate" label="品项启动日期" align="center" width="140">
        <template slot-scope="{ row }">{{ row.prodLaunchDate ? row.prodLaunchDate.substring(0, 11) : '--' }}</template>
      </el-table-column>
      <el-table-column prop="salesVolume" label="销量" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.salesVolume" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="customerFeedback" label="顾客反馈" align="center" width="105">
        <template slot-scope="{ row }">
          <el-rate v-model="row.customerFeedback" :max="3" disabled></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="monthlyPerformancePct" label="占月业绩百分比" align="center" width="140"></el-table-column>
      <el-table-column prop="createDate" label="创建日期" align="center" width="120">
        <template slot-scope="{ row }">{{ row.createDate ? row.createDate.substring(0, 11) : '--' }}</template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="120">
        <template slot="header">
          <el-button type="primary" size="mini" plain @click.stop="handleAddEmptyRow">添加一行</el-button>
        </template>
        <template slot-scope="{ row }">
          <el-button v-if="row.id && row.id > 0" type="danger" size="mini" plain @click.stop="handleDelete(row)">
            删除
          </el-button>
          <el-button v-else type="warning" size="mini" plain @click.stop="handleDeleteRow(row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { delProdDiagnoseById, geProdDiagnoseByNo, saveProdDiagnoseByNo } from '@/api/diagnose';
// 引入自定义组件
import '@/utils/datefmt';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const EmptyProdData = {
  id: undefined,
  prodName: '', // NOT NULL
  prodPosition: undefined, // NOT NULL
  operablePeriod: undefined, // NOT NULL
  salesResponsibleParty: '',
  salesMethod: 1,
  actualPrice: 0.0,
  grossMargin: 0.0,
  prodLaunchDate: new Date().format('yyyy-MM-dd'),
  salesVolume: undefined, // NOT NULL
  customerFeedback: undefined, // NOT NULL
  monthlyPerformancePct: undefined, // NOT NULL
  coachId: null,
  coachName: null,
  createDate: null,
  __fid: '', // Form 表单ID
};

const EnumSalesMethod = [
  { code: 1, name: '定价销售' },
  { code: 2, name: '议价销售' },
];
const EnumProdPosition = [
  { code: 1, name: '引流产品/到院目的' },
  { code: 2, name: '短期留客产品/二次到院' },
  { code: 3, name: '长期锁客产品/长期到院' },
  { code: 4, name: '利润产品' },
  { code: 5, name: '形象产品' },
];

export default {
  name: 'Diagnose7',
  filters: {
    fltSalesMethod(val) {
      const tmp = EnumSalesMethod.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
    fltProdPosition(val) {
      const tmp = EnumProdPosition.find(x => x.code == val);
      if (tmp) {
        return tmp.name;
      }
      return '';
    },
  },
  data() {
    return {
      tableData: [],
      salon: {},
      rules: {
        prodName: [{ required: true, message: '品项名称不能为空', trigger: 'blur' }],
        prodPosition: [{ required: true, message: '品项定位不能为空', trigger: 'blur' }],
        operablePeriod: [{ required: true, message: '可操作周期不能为空', trigger: 'blur' }],
        salesVolume: [{ required: true, message: '销量不能为空', trigger: 'blur' }],
        customerFeedback: [{ required: true, message: '顾客反馈不能为空', trigger: 'blur' }],
        monthlyPerformancePct: [{ required: true, message: '占月业绩百分比不能为空', trigger: 'blur' }],
      },
      EnumSalesMethod: EnumSalesMethod,
      EnumProdPosition: EnumProdPosition,
      isFetching: false, // 通用的&互斥的, 加载后端数据
      isUpdating: false,
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
  },
  created() {},
  methods: {
    loadDiagnoseData: async function (salon /* {salonId: '', salonNo: '', salonName: '', diagnoseNo: ''} */) {
      if (!salon || !salon.diagnoseNo) {
        return;
      }
      this.salon = Object.assign({}, salon);
      this.loadDiagnose7();
    },
    loadDiagnose7: async function () {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      this.tableData.splice(0, this.tableData.length);
      const errAlertMsg = '查询产品复盘失败';
      await geProdDiagnoseByNo(this.salon.diagnoseNo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length > 0) {
            ret.forEach(x => {
              x.__fid = this.getRadomStr6();
              this.tableData.push(x);
            });
          }
        })
        .catch(err => {
          console.log('geProdDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleAddEmptyRow: async function () {
      const cpy = Object.assign({}, EmptyProdData);
      cpy.coachName = this.name;
      cpy.__fid = this.getRadomStr6();
      this.tableData.push(cpy);
    },
    handleDelete: async function (row) {
      const errAlertMsg = '删除产品复盘失败';
      delProdDiagnoseById(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.handleDeleteRow(row);
        })
        .catch(err => {
          console.log('delProdDiagnoseById', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    handleDeleteRow: async function (row) {
      // 根据 index 从 this.tableData 中将数据删除
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    picDisabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return !(date - today < 0);
    },
    getRadomStr6() {
      // 生成长度为 6 的随机字符串
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    handleSubmitForm: async function (formName, isadd, row) {
      // Validate row data against rules
      for (const key in this.rules) {
        if (this.rules.hasOwnProperty(key)) {
          const rule = this.rules[key][0];
          if (rule.required && (row[key] === undefined || row[key] === null)) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'array' && row[key].length < rule.min) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'number' && typeof row[key] !== 'number') {
            MessageBox.alert(rule.message);
            return;
          }
        }
      }

      if (row.id <= 0) {
        row.id = null;
      }

      this.isUpdating = true;
      const errAlertMsg = '保存产品复盘失败';
      saveProdDiagnoseByNo(this.salon.diagnoseNo, row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadDiagnose7();
          MessageBox.alert('保存成功');
        })
        .catch(err => {
          console.log('saveProdDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.table_expand {
  padding: 5px 16px;
  font-size: 0;
  background-color: rgb(249, 243, 234);

  .star_level {
    width: 180px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
  }
}
.table_expand label {
  width: 90px;
  color: #99a9bf;
}
.table_expand .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 50%;
}
</style>
